﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace spec_unsafe.Fixed
{
    //这个代码安全吗？如果每次都判断ptr是不是zero，安全吗？
    class SomeBadCode
    {
        public IntPtr ptr;
        byte[] realbyte;
        public SomeBadCode()
        {
            realbyte = new byte[32];
            unsafe
            {
                fixed (byte* bts = realbyte)
                {
                    ptr = (IntPtr)bts;
                }
            }
        }
    }
    //这个代码安全吗？如果每次都判断ptr是不是null，安全嘛？
    class SomeBadCode2
    {
        public unsafe byte* ptr;
        byte[] realbyte;
        public SomeBadCode2()
        {
            realbyte = new byte[32];
            unsafe
            {
                fixed (byte* bts = realbyte)
                {
                    ptr = bts;
                }
            }
        }
    }

    class SomeBetterCode
    {
        public IntPtr ptr
        {
            get
            {
                unsafe
                {
                    fixed (byte* bts = realbyte)
                    {
                        return (IntPtr)bts;
                    }
                }
            }
        }
        byte[] realbyte;
        public SomeBetterCode()
        {
            realbyte = new byte[32];
        }
    }

    class FinalSafeCode
    {

        byte[] realbyte;
        public FinalSafeCode()
        {
            realbyte = new byte[32];
        }

        GCHandle gclock;
        public IntPtr Lock()
        {
            gclock= GCHandle.Alloc(this.realbyte, GCHandleType.Pinned);
            unsafe
            {
                fixed (byte* bts = realbyte)
                {
                    return (IntPtr)bts;
                }
            }
        }
        public void Unlock()
        {
            gclock.Free();
        }
    }
    class @fixed
    {
    }
}
